<template>
  <view>
    <view class="login-wrap" v-if="isShow == true" :data-theme="globPrimary">
      <u-navbar title="绑定" :custom-back="onBack"></u-navbar>
      <u-form :model="verify" ref="verifyForm" :error-type="errorType" label-width="120rpx">
        <u-form-item label="+86" left-icon="arrow-down" prop="phone"
          ><u-input v-model="verify.phone" placeholder="请输入手机号" type="number"
        /></u-form-item>
        <u-form-item label="验证码" prop="verify">
          <u-input placeholder="请输入验证码" v-model="verify.verify" type="text"></u-input>
          <u-button
            slot="right"
            size="mini"
            @click="handleGetCode"
            :disabled="verifyDisabled || codeType"
            :class="[codeType ? 'code-disabled' : '']"
            class="code-btn"
          >
            {{ codeTips }}
          </u-button>
        </u-form-item>
      </u-form>
      <edu-button class="verify-btn" type="primary" @click="handleVerifySubmit">绑定</edu-button>
      <u-verification-code
        seconds="60"
        ref="uCode"
        @change="codeChange"
        @end="codeEnd"
        @start="codeStart"
      ></u-verification-code>
      <u-toast ref="uToast" />
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import setting from '@/settings/projectSetting.js'
export default {
  data() {
    return {
      setting,
      code: '',
      state: '',
      oauth: '',
      isShow: false,

      verify: {
        phone: '',
        verify: '',
      },
      rulesVerify: {
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          },
        ],
        verify: [
          {
            required: true,
            message: '请输入验证码',
            trigger: ['change', 'blur'],
          },
        ],
      },
      codeTips: '',
      codeType: true,
      errorType: ['message'],
    }
  },
  computed: {
    ...mapGetters({
      globAppTitle: 'projectSetting/getGlobTitle',
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
      hasLogin: 'user/getHasLogin',
    }),
    verifyDisabled() {
      let disabled = true
      if (this.$u.test.mobile(this.verify.phone)) {
        this.codeType = false
        disabled = false
      } else {
        this.codeType = true
      }
      return disabled
    },
  },
  onLoad(option) {
    this.code = option.code
    this.state = option.state
    if (option.oauth) {
      this.oauth = option.oauth
    }
    if (option.state == 'qq') {
      // qq登录
      this.bindQqLogin()
    } else if (option.state == 'weixin') {
      // 微信登录
      this.bindWxLogin()
    } else if (option.state == 'openid') {
      this.getOpenid()
    }
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    if (this.isShow) {
      this.$refs.verifyForm.setRules(this.rulesVerify)
    }
  },
  methods: {
    handleVerifySubmit() {
      this.$refs.verifyForm.validate((valid) => {
        if (valid) {
          let verify = {
            type: this.state,
            oauth: this.oauth,
            phone: this.verify.phone,
            verify: this.verify.verify,
          }
          this.starBind(
            verify,
            (res) => {
              this.$u.toast(res.msg)
              this.handleLoginSucc(res.data)
            },
            (err) => {
              this.$u.toast(err.msg)
            }
          )
        }
      })
    },
    // 获取验证码
    handleGetCode() {
      if (this.$refs.uCode.canGetCode) {
        this.$edu.api
          .createVerify({
            phone: this.verify.phone,
            type: 'bind_weixin',
          })
          .then((res) => {
            this.$refs.uCode.start()
          })
      }
    },
    // 倒计时
    codeChange(text) {
      this.codeTips = text
    },
    // 倒计时开始
    codeStart() {
      this.codeType = true
    },
    // 倒计时结束
    codeEnd() {
      this.codeType = false
    },
    getUrlCode(name) {
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [
            ,
            '',
          ])[1].replace(/\+/g, '%20')
        ) || null
      )
    },
    // 三方登录
    bindWxLogin() {
      let phone = ''
      if (!this.$u.test.empty(this.userInfo)) {
        phone = this.userInfo.phone
      }
      this.phone = phone
      // #ifdef H5
      this.$edu.api
        .getWechatLogin({
          phone: phone,
          code: this.code,
        })
        .then((res) => {
          if (res.data.has_bind == 0) {
            // 是未绑定无手机号
            this.isShow = true
            this.oauth = res.data.oauth
          } else if (res.data.has_bind == 1) {
            uni.$u.route({
              type: 'redirectTo',
              url: '/pageUser/setting/thirdlogin',
            })
            this.$store.dispatch('user/setUserInfo')
          } else if (res.data.has_bind == 2) {
            // 是已绑定
            this.handleLoginSucc(res.data.user)
          }

          // 用户openid
          this.$store.dispatch('projectSetting/setGlobWeixinAppid')
        })
        .catch((res) => {})
      // #endif
      // #ifdef APP-PLUS
      this.isShow = true
      // #endif
    },
    // qq登录
    bindQqLogin() {
      let phone = ''
      if (!this.$u.test.empty(this.userInfo)) {
        phone = this.userInfo.phone
      }
      this.phone = phone
      // #ifdef H5
      this.$edu.api
        .getConfigThirdloginCheck({
          type: this.state,
          code: this.code,
          redirect_uri: this.setting.appBaseUrl + '/pageUser/setting/wechatLogin',
        })
        .then((res) => {
          if (this.hasLogin) {
            let verify = {
              type: this.state,
              oauth: res.data.oauth,
            }
            this.starBind(
              verify,
              (res) => {
                this.$u.toast(res.msg)
                uni.$u.route({
                  type: 'redirectTo',
                  url: '/pageUser/setting/thirdlogin',
                })
              },
              (err) => {
                this.$u.toast(err.msg)
                uni.$u.route({
                  type: 'redirectTo',
                  url: '/pageUser/setting/thirdlogin',
                })
              }
            )
          } else {
            if (res.data.has_bind == 1) {
              // 已绑定
              this.handleLoginSucc(res.data.user)
            } else {
              this.isShow = true
              this.oauth = res.data.oauth
            }
          }
          // 用户openid
          this.$store.dispatch('projectSetting/setGlobWeixinAppid')
        })
        .catch((res) => {})
      // #endif
      // #ifdef APP-PLUS
      this.isShow = true
      // #endif
    },
    starBind(verify, success, error) {
      this.$edu.api
        .postBindLogin(verify)
        .then((res) => {
          success(res)
        })
        .catch((error) => {
          error(error)
        })
    },
    handleLoginSucc(data) {
      this.onBack()
      this.$store.commit('user/setToken', data)
      // 获取个人信息
      this.$store.dispatch('user/setUserInfo')
      // 设置用户头像
      this.$store.commit('user/setAvatar', data.avatar_url)
    },
    getOpenid() {
      //code已授权，获取openId
      this.$edu.api
        .getConfigOpenid({
          code: this.code,
        })
        .then((res) => {
          const { data } = res
          this.$store.commit('projectSetting/comGlobConfigopenid', data)
          uni.$u.route({ type: 'switchTab', url: '/pages/user/index' })
        })
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      if (this.$u.test.empty(page)) {
        uni.$u.route({ type: 'switchTab', url: '/pages/user/index' })
      } else {
        this.$u.route({ type: 'back' })
      }
    },
  },
}
</script>
<style lang="scss">
page {
  background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.login-wrap {
  padding: 0 30rpx;
  background-color: #fff;
  /deep/.u-form-item {
    color: #606266;
    .u-form-item--left__content {
      flex-direction: row-reverse;
    }
  }
  .verify-btn {
    margin-top: 170rpx;
  }
  .loginBtn {
    height: 80rpx;
    width: 690rpx;
    margin: 170rpx auto 0;
    text-align: center;
    line-height: 80rpx;
    color: white;
    font-size: 30rpx;
    text-align: center;
    border-radius: 10rpx;
  }
  .code-btn {
    @include text-color();
    border: none;
    padding: 0;
    background-color: #fff;
    &::after {
      border: none;
    }
  }
  .code-disabled {
    color: #b7bac1;
  }
}
</style>
